<?php

require_once 'RestUtils.php';
require_once 'dbutils.php';
require_once 'Base.php';

class CheckAuth extends Base
{

    function GET($matches)
    {
        $req = RestUtils::processRequest('GET');
        $req_vars = $req->getRequestVars();
        $this->getAuthToken($req_vars);
    }

    function POST($matches)
    {
        $req = RestUtils::processRequest('POST');
        $req_vars = $req->getRequestVars();
        $this->getAuthToken($req_vars);
    }


    private function http_post($url, $data)
    {
        $data_url = http_build_query($data);
        $data_len = strlen($data_url);

        return array('content' => file_get_contents($url, false, stream_context_create(array('http' => array('method' => 'POST'
        , 'header' => "Connection: close\r\nContent-Length: $data_len\r\n"
        , 'content' => $data_url
        ))))
        , 'headers' => $http_response_header
        );
    }


    private function insertUserOpenIdEmail($values)
    {
        $code = 0;
        $msg = '';
        $result = null;
        try {
            if (!$values)
                return array('code' => -1, 'message' => 'required request parameters not found', 'result' => null);

            if (!array_key_exists('cd_contact', $values)
                || !array_key_exists('ds_contact', $values)
                || !array_key_exists('priority', $values)
                || !array_key_exists('openid', $values)
                || !array_key_exists('username', $values)
                || !array_key_exists('gender', $values)
                || !array_key_exists('nationality', $values)
                || !array_key_exists('birth_year', $values)
                || !array_key_exists('fl_on_line', $values)
            )
                return array('code' => -1, 'message' => 'required request parameters not found', 'result' => null);

            $db_handle = @pg_pconnect(dbutils::$conn_string);

            $res = @pg_query($db_handle, "SELECT nextval('users_id_seq') as key");
            if ($res) {
                $row = @pg_fetch_array($res, 0);
                $id_user = $row['key'];
            }

            if ($id_user) {
                $insert = "INSERT INTO contacts (id_user,
                                                 cd_contact,
                                                 ds_contact,
                                                 priority)
                                         VALUES ({$id_user},
                                                 '{$values['cd_contact']}',
                                                 '{$values['ds_contact']}',
                                                 {$values['priority']});";
                $insert .= " INSERT INTO users (id,
                                                openid,
                                                username,
                                                gender,
                                                nationality,
                                                birth_year,
                                                fl_on_line)
                                        VALUES ({$id_user},
                                               '{$values['openid']}',
                                               '{$values['username']}',
                                               '{$values['gender']}',
                                               '{$values['nationality']}',
                                               '{$values['birth_year']}',
                                               '{$values['fl_on_line']}');";

                $result = @pg_query($db_handle, $insert);

                if ($result)
                    $result = json_encode(array('idUser' => $id_user, 'openid' => $values['openid']));
                else {
                    $code = -1;
                    $msg = 'inserting records not possible ' . @pg_last_error($db_handle);
                }

            } else {
                $code = -1;
                $msg = 'error generating idUser ' . @pg_last_error($db_handle);
            }

            @pg_close($db_handle);

        } catch (Exception $e) {
            $code = $e->getCode();
            $msg = $e->getMessage();
        }
        return array('code' => $code, 'message' => $msg, 'result' => $result);
    }


    private function validateWithServer($query)
    {
        if (!array_key_exists('openid_op_endpoint', $query)
            || !array_key_exists('openid_assoc_handle', $query)
            || !array_key_exists('openid_signed', $query)
            || !array_key_exists('openid_sig', $query)
        )
            return false;

        $openid_server = $query['openid_op_endpoint'];

        $params = array(
            'openid.assoc_handle' => $query['openid_assoc_handle'],
            'openid.signed' => $query['openid_signed'],
            'openid.sig' => $query['openid_sig']
        );
        // Send only required parameters to confirm validity
        $arr_signed = explode(",", $query['openid_signed']);
        for ($i = 0; $i < count($arr_signed); $i++) {
            $s = $arr_signed[$i];
            $params['openid.' . $s] = $query['openid_' . str_replace('.', '_', $s)];
        }
        $params['openid.mode'] = "check_authentication";

        $response = $this->http_post($openid_server, $params);
        $data = $response['content'];

        return stripos($data, 'is_valid:true') !== false;
    }

    private function getAuthToken($data)
    {

        if ($this->validateWithServer($data)) {

            session_start();
            $_SESSION['SIGNATURE'] = md5("SIGNATURE=" . md5($_SERVER['HTTP_USER_AGENT']));
            $_SESSION['IDENTITY'] = $data['openid_identity'];

            $table = 'users';
            $query_data = array('openid' => $data['openid_identity']);
            //        $query_data = array('email' => $data['openid_ext1_value_email'], 'openid' => $data['openid_identity']);
            $db_handle = @pg_pconnect(dbutils::$conn_string);
            $sel_result = @pg_select($db_handle, $table, $query_data);
            if (!$sel_result || count($sel_result) == 0) {
                $values['cd_contact'] = 'EMAIL';
                $values['ds_contact'] = $data['openid_ext1_value_email'];
                $values['priority'] = 0;
                $values['openid'] = $data['openid_identity'];
                $values['username'] = md5($data['openid_identity']);
                $values['gender'] = 'M';
                $values['nationality'] = 'IT';
                $values['birth_year'] = '1999';
                $values['fl_on_line'] = 't';

                $ins_result = $this->insertUserOpenIdEmail($values);
            }
        }
        if ($ins_result) {

            if ($ins_result['code'] == 0)
                RestUtils::sendResponse(200, $ins_result['result'], 'application/json');
            else
                RestUtils::sendResponse(404, dbutils::error_to_json($ins_result['code'], $ins_result['message']), 'application/json');
        } elseif ($sel_result)
            RestUtils::sendResponse(200, json_encode(dbutils::translate_db_params($sel_result[0])), 'application/json');
        else
            RestUtils::sendResponse(401);
    }
}

?>
